from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy import desc, func, select
from sqlalchemy.orm import Session
from typing import List, Literal, Optional
import math
import aiohttp
from datetime import datetime
import json

from app.core.security import get_current_user
from app.database import get_db
from app.models.announcement import Announcement
from app.models import Admin
from app.services.announcement import AnnouncementService

router = APIRouter(prefix="/announcement")

@router.get("/filter")
async def get_announcements(
    page: int = Query(1),
    size: int = Query(10),
    locations: Optional[Literal["0", "1", ""]] = Query(None),
    sort_by: Optional[Literal["0", "1", ""]] = Query(None),
    categories: Optional[List[str]] = Query(None),
    query: Optional[str] = Query(None),
    db: Session = Depends(get_db),
):
    """获取公告列表"""
    try:
        page = int(page)
        size = int(size)
        locations = (int(locations) if len(locations) > 0 else None) if locations else None
        sort_by = (int(sort_by) if len(sort_by) > 0 else None) if sort_by else 0
        # categories = [int(i) for i in categories] if categories else None
        query = str(query) if query else None

        service = AnnouncementService(db)
        result = await service.get_announcement_filter(page, size, query, locations, sort_by)
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail={"code": 50000, "data": str(e)})


@router.get("/{id}/detail")
async def get_announcement_detail(id: int, db: Session = Depends(get_db)):
    """获取公告详情"""
    try:
        service = AnnouncementService(db)
        result = await service.get_announcement_detail(id)
        return result
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail={"code": 50000, "data": str(e)})


@router.get("/{id}/content")
async def get_announcement_content(id: int, db: Session = Depends(get_db)):
    """获取公告内容"""
    try:
        
        service = AnnouncementService(db)
        result = await service.get_announcement_content(id)
        return result
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail={"code": 50000, "data": str(e)})


@router.get("/{id}/poster")
async def get_announcement_poster(id: int, db: Session = Depends(get_db)):
    """获取公告海报"""
    try:
        service = AnnouncementService(db)
        result = await service.get_announcement_poster(id)
        return result
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail={"code": 50000, "data": str(e)})
